package com.cmdi.mq.controller;

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.cmdi.mq.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * @Description: 获取sentinel的限流规则
 * @Author: gaozb
 */
@Slf4j
@RestController
@RequestMapping("/gw")
public class GatewayFlowRulesController {
    public final static String GW_OPERATION_PERMIS = "sys_gw_ops";
    @Value("${gw.key:abcd}")
    private String key;



    /**
     * 获取网关的限流策略
     **/
    @RequestMapping("/rules")
    public Set<GatewayFlowRule> getGatewayFlowRuleSet(ServerHttpRequest request) {
        if(hasP(request)) {
            return GatewayRuleManager.getRules();
        }
        return null;
    }

    /**
     * 获取当自定义API分组
     **/
    @RequestMapping("/apirules")
    public Set<ApiDefinition> geApiGroups(ServerHttpRequest request) {
        if(hasP(request)) {
            return GatewayApiDefinitionManager.getApiDefinitions();
        }
        return null;

    }

    /**
     * 获取非网关普通的限流策略
     **/
    @RequestMapping("/flows")
    public List<FlowRule> getFlows(ServerHttpRequest request) {
        if(hasP(request)) {
            return FlowRuleManager.getRules();
        }
        return null;

    }

    public boolean hasP(ServerHttpRequest request) {
        String first = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        log.info("first : {}", first);
        if(first != null) {
            return JwtUtil.hasPerms(first, GW_OPERATION_PERMIS);
        }
        return false;
    }
}